package com.xiaozhen.jt809.handler;

import com.xiaozhen.jt809.constant.JT809BusinessConstant;
import com.xiaozhen.jt809.handler.client.DownConnectHandler;
import com.xiaozhen.jt809.handler.client.DownLinkTestHandler;
import com.xiaozhen.jt809.handler.client.UpCloseLinkInformHandler;
import com.xiaozhen.jt809.handler.client.UpDisconnectInformHander;
import com.xiaozhen.jt809.handler.server.*;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/16 14:35
 * @description:
 */
@Component
public class CommonHandlerFactory implements ApplicationContextAware {
    private static Map<Integer, MyHandler> handlers = new ConcurrentHashMap<>();
    private static ApplicationContext context;


    @PostConstruct
    public void serverHandlerFactory() {
        //主链路
        handlers.put(JT809BusinessConstant.UP_CONNECT_REQ, context.getBean(UpConnectHandler.class));
        handlers.put(JT809BusinessConstant.UP_LINKTEST_REQ, context.getBean(UpLinkHandler.class));
        handlers.put(JT809BusinessConstant.UP_DISCONNECT_REQ, context.getBean(UpDisconnectHandler.class));
        handlers.put(JT809BusinessConstant.UP_EXG_MSG, context.getBean(UpExgMsgHandler.class));
        handlers.put(JT809BusinessConstant.UP_WARN_MSG, context.getBean(UpWarnHandler.class));
        //从链路
        handlers.put(JT809BusinessConstant.DOWN_CONNECT_RSP, context.getBean(DownConnectHandler.class));
        handlers.put(JT809BusinessConstant.UP_DISCONNECT_INFORM, context.getBean(UpDisconnectInformHander.class));
        handlers.put(JT809BusinessConstant.DOWN_LINKTEST_RSP, context.getBean(DownLinkTestHandler.class));
        handlers.put(JT809BusinessConstant.UP_CLOSELINK_INFORM, context.getBean(UpCloseLinkInformHandler.class));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (null == context) {
            context = applicationContext;
        }
    }

    public MyHandler getHandler(Integer msgId) {
        return handlers.get(msgId);
    }


}
